package com.dingwen.treasure.open.api.tx.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.util.Assert;

/**
 * tx服务
 *
 * @author dingwen
 * @date 2023/01/11
 */
public interface TxService {
    Integer SUCCESS_CODE = 200;
    String RESULT_KEY = "result";
    String CONTENT_KEY = "content";
    String CODE_KEY = "code";

    String KEY_KEY = "key";

    /**
     * 获取一个
     *
     * @param url url
     * @param key 关键
     * @param msg 消息
     * @return {@link String}
     */
    default String fetchOne(String url, String key, String msg) {
        String result = HttpUtil.get(url.concat("?")
                .concat(KEY_KEY)
                .concat("=")
                .concat(key)
        );
        Assert.isTrue(StrUtil.isNotBlank(result) && JSONUtil.isJson(result), "返回结果空或不是JSON");
        JSONObject re = JSONUtil.parseObj(result);

        if (!SUCCESS_CODE.equals(re.get(CODE_KEY))) {
            Assert.isTrue(false, msg);
        }
        JSONObject data = re.get(RESULT_KEY, JSONObject.class);
        return data.get(CONTENT_KEY, String.class);
    }
}
